package jy.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import jy.pageModel.Json;
import jy.pageModel.PUser;
import jy.pageModel.SessionInfo;
import jy.service.UserServiceI;
import jy.util.ConfigUtil;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 用户控制器
 * 
 * @author JY
 * 
 */
@Controller
@RequestMapping("/user")
public class UserController extends BaseController {

	@Autowired
	private UserServiceI userService;

	@RequestMapping("/showUser")
	public String showUser(Integer id,HttpServletRequest request){

		PUser u = userService.get(id);
		request.setAttribute("user", u);
		return "showUser";
	}


	/**
	 * 用户登录
	 * 
	 * @param user
	 *            用户对象
	 * @param session
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/login")
	public Json login(PUser user, HttpSession session, HttpServletRequest request) {
		Json j = new Json();
		PUser u = userService.login(user);
		if (u != null) {
			j.setSuccess(true);
			j.setMsg("登陆成功！");

			SessionInfo sessionInfo = new SessionInfo();
			BeanUtils.copyProperties(u, sessionInfo);
			sessionInfo.setName(u.getPname());
			session.setAttribute(ConfigUtil.getSessionInfoName(), sessionInfo);

			j.setObj(sessionInfo);
		} else {
			j.setMsg("用户名或密码错误！");
		}
		return j;
	}

	/**
	 * 用户注册
	 * 
	 * @param user
	 *            用户对象
	 * @return
	 */
	@ResponseBody //用来返回json
	@RequestMapping("/reg")
	public Json reg(PUser user) {
		Json j = new Json();
		try {
			userService.reg(user);
			j.setSuccess(true);
			j.setMsg("注册成功！新注册的用户没有任何权限，请让管理员赋予权限后再使用本系统！");
			j.setObj(user);
		} catch (Exception e) {
			// e.printStackTrace();
			j.setMsg(e.getMessage());
		}
		return j;
	}
	
	@ResponseBody
	@RequestMapping("/shopreg")
	public Json shopreg(PUser user) {
		System.out.println(user.getArea());
		System.out.println(user.getInfo());
		user.setCity("none");
		Json j = new Json();		
		try {
			userService.shopreg(user);
			j.setSuccess(true);
			j.setMsg("注册成功！新注册的用户没有任何权限，请让管理员赋予权限后再使用本系统！");
			j.setObj(user);
		} catch (Exception e) {
			// e.printStackTrace();
			j.setMsg(e.getMessage());
		}
		
		return j;
	}

	/**
	 * 退出登录
	 * 
	 * @param session
	 * @return
	 */
	@RequestMapping("/logout")
	public String logout(HttpSession session) {
		Json j = new Json();
		if (session != null) {
			session.invalidate();
		}
		j.setSuccess(true);
		j.setMsg("注销成功！");
		return "redirect:/";
	}


}
